<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\25 0025
 * Time: 9:52
 */

namespace app\Lib\Model\SysConfig\SysConfigManage;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\SysConfig\SysConfig;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\DbModel\AdminConfig;

class EditConfig extends ConfigCommon implements  \app\Lib\InterfaceIn\SysConfig\SysConfigManage\EditConfig
{
    private $id;
    /** @var UserHandle $opUser */
    private $opUser;

    /**
     * 修改初始化
     * EditConfig constructor.
     * @param $id
     * @param UserHandle $opUser
     */
    public function __construct($id, UserHandle $opUser)
    {
        $this->id       = $id;
        $this->opUser   = $opUser;
    }


    /**
     * 执行代码
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function run()
    {
        $model                      = $this->getTable();
        $data                       = $this->handleArray();
        $validate                   = $this->getValidate();
        $data[$model->_id]          = $this->id;
        $data[$model->_update_uid]  = $this->opUser->getUid();
        $data[$model->_update_time] = time();
        $this->validate($data);
        if(!($validate->scene('editRole')->check($data))){
            throw new BlException($validate->getError());
        }
        $result                     = $model->update($data);
        if(!$result){
            throw new BlException('修改失败');
        }
        /*删除缓存*/
        SysConfig::delValue($data['variable']);
        return true;
    }

    /**
     * 参数验证
     * @param $data
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function validate($data){
        $model= $this->getTable();
        $info = $model->where($model->_status,1)->where(function ($query)use($data){
            $models =$this->getTable();
            /**@var AdminConfig $query  */
            $query->whereOr($models->_title,$data[$models->_title])->whereOr($models->_variable,$data[$models->_variable]);
        })->where([$model->_id=>['neq',$this->id]])->field([$model->_title,$model->_variable])->find();
        if($info && $info[$model->_title] == $data[$model->_title]){
            throw new BlException('配置标题已存在');
        }
        if($info && $info[$model->_variable] == $data[$model->_variable]){
            throw new BlException('配置key已存在');
        }
        return true;
    }

}